<!--
 * @Author: weikang
 * @Description:
 * @Date: 2024-01-21 16:34:04
 * @LastEditTime: 2025-04-07 21:54:59
 * @FilePath: \env-manager-pc\src\views\electricity_statistics\by.day\by.day.detail.vue
-->
<script setup lang="ts">
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'
import EntDeviceTreeCheck from '../EntDeviceTreeCheck/index.vue'
import detailTable from './components/detail.table.vue'
import eleStatisticsApi from '@/api/modules/ele.statistics'
import useKeepAliveStore from '@/store/modules/keepAlive'
import type { PolluteErrRow } from '@/api/modules/types/data.query'
import useUserStore from '@/store/modules/user'

const keepAliveStore = useKeepAliveStore()
const userStore = useUserStore()

onBeforeRouteLeave((to) => {
  if (to.name !== 'electricity-statistics-bymonth-list') {
    keepAliveStore.remove('DataEntDayPowerList')
  }
})
const route = useRoute()
const currentDevices = ref<any>([])

const isDay = computed(() => {
  const routeName = route.name as string
  return routeName?.includes('byday')
})

function currentChange(nodes: any[]) {
  const mapId: any = []
  const devices: any = []
  nodes.forEach((item) => {
    if (!mapId.includes(item.ObjID)) {
      devices.push(item)
      mapId.push(item.ObjID)
    }
  })
  currentDevices.value = devices
  getData()
}

const cwRef = ref()
const entData = reactive(sessionStorage.getItem('PolluteErrRow') ? JSON.parse(sessionStorage.getItem('PolluteErrRow') as string) : {},
)
const deviceInfo: PolluteErrRow = JSON.parse(sessionStorage.getItem('PolluteErrRow') || '{}')
const deviceId = route.params.id as string
// const type = route.query.type as DeviceType
const loading = ref(false)
const tableData = ref<any>([])

const currentTime = ref(dayjs().format('YYYY-MM-DD HH:mm:ss'))

const startTime = ref<string>(route.query.startTime as string || (isDay.value ? dayjs().subtract(30, 'day').format('YYYYMMDD') : dayjs().subtract(12, 'month').format('YYYYMMDD')))
const endTime = ref<string>(route.query.endTime as string || dayjs().format('YYYYMMDD'))

const searchTime = computed({
  set: (value) => {
    const [start, end] = value
    startTime.value = start
    endTime.value = end
  },
  get: () => {
    return [startTime.value, endTime.value]
  },
})
function changeTime(value: any) {
  currentTime.value = value
  getData()
}

const columns = ref<any>([])

async function getData() {
  if (!currentDevices.value.length) {
    return ElMessage.warning('请先勾选设备')
  }
  try {
    loading.value = true
    const api = isDay.value ? eleStatisticsApi.GetElectricityDay : eleStatisticsApi.GetElectricityMonth
    const res = await api({
      deviceObjIDs: currentDevices.value.map((item: any) => item.ObjID),
      startTime: startTime.value,
      endTime: dayjs(endTime.value).add(1, 'day').format('YYYYMMDD'),
    })
    columns.value = []
    loading.value = false
    tableData.value = Object.entries(currentDevices.value).map(([index, obj]: any) => {
      if (Number(index) === 0) {
        Object.keys(res[obj.ObjID]).forEach((key: string) => {
          columns.value.push({
            title: key,
            field: key,
            slots: { default: 'name_default' },
            width: 130,
          })
        })
      }
      return {
        ...obj,
        ...res[obj.ObjID],
      }
    })
    columns.value = columns.value.sort((aRow: any, bRow: any) => new Date(aRow.title).getTime() - new Date(bRow.title).getTime())
  }
  catch (e) {
    loading.value = false
  }
}

function outPut() {
  if (!currentDevices.value.length) {
    return ElMessage.warning('请先勾选设备')
  }
  const api = isDay.value ? eleStatisticsApi.GetElectricityDayToExcel : eleStatisticsApi.GetElectricityMonthToExcel
  const params = {
    deviceObjIDs: currentDevices.value.map((item: any) => item.ObjID),
    startTime: startTime.value,
    endTime: dayjs(endTime.value).add(1, 'day').format('YYYYMMDD'),
  }
  api(params).then((res: any) => {
    // 从响应头中获取文件名
    const contentDisposition = res.headers['content-disposition']
    let fileName = 'downloaded_file' // 默认文件名
    const prefix = 'attachment;filename='
    if (contentDisposition.startsWith(prefix)) {
      fileName = contentDisposition.slice(prefix.length)
    }

    // 创建 Blob 对象
    const urlBlob = window.URL.createObjectURL(new Blob([res.data]))

    // 创建 a 标签并触发下载
    const link = document.createElement('a')
    link.href = urlBlob
    link.setAttribute('download', decodeURIComponent(fileName))
    document.body.appendChild(link)
    link.click()

    // 移除 a 标签
    link.remove()
    window.URL.revokeObjectURL(urlBlob)
  })
}
</script>

<template>
  <PageMain>
    <div class="flex">
      <div class="mr-20px w-300px flex-shrink-0 b-r-1px b-r-#EBEEF5 b-r-solid pr-10px">
        <EntDeviceTreeCheck :ent-id="deviceInfo.EntObjID" :device-id="deviceId" @current-change="currentChange" />
      </div>
      <div class="flex-grow-1 overflow-x-hidden">
        <div>
          <ElDatePicker v-model="searchTime" type="daterange" value-format="YYYYMMDD" placeholder="选择日期" :clearable="false" @change="changeTime" />
          <el-tag v-if="!userStore.isEnterpris && entData.EntName" class="ml-10px" size="large" type="primary">
            企业：{{ entData.EntName }}
          </el-tag>
          <ElButton type="primary" class="ml-2" @click="outPut">
            导出
          </ElButton>
        </div>
        <div class="mt-10px">
          <detailTable
            ref="cwRef"
            :loading="loading"
            :table-data="tableData"
            :columns="columns"
          />
        </div>
      </div>
    </div>
  </PageMain>
</template>
